using PdfiumViewer;
using System.Diagnostics;

namespace PrintTool.Forms;

public partial class PdfPreviewForm : Form
{
    private readonly string pdfFilePath;
    private PdfViewer pdfViewer;
    private Stream? pdfStream;
    private PdfDocument? pdfDocument;

    public PdfPreviewForm(string pdfPath)
    {
        pdfFilePath = pdfPath;
        InitializeComponent();
        LoadPdf();
    }

    private void InitializeComponent()
    {
        this.Text = $"PDF预览 - {Path.GetFileName(pdfFilePath)}";
        this.Size = new Size(1000, 800);
        this.StartPosition = FormStartPosition.CenterParent;
        this.WindowState = FormWindowState.Maximized;

        // 创建工具栏
        var toolStrip = new ToolStrip();
        
        var btnFitWidth = new ToolStripButton("适应宽度", null, BtnFitWidth_Click);
        var btnFitBest = new ToolStripButton("适应最佳", null, BtnFitBest_Click);
        var btnOpenFolder = new ToolStripButton("打开文件夹", null, BtnOpenFolder_Click);
        
        // 设置按钮样式
        btnFitWidth.DisplayStyle = ToolStripItemDisplayStyle.Text;
        btnFitBest.DisplayStyle = ToolStripItemDisplayStyle.Text;
        btnOpenFolder.DisplayStyle = ToolStripItemDisplayStyle.Text;
        
        toolStrip.Items.AddRange(new ToolStripItem[]
        {
            btnFitWidth,
            btnFitBest,
            new ToolStripSeparator(),
            btnOpenFolder
        });

        // 创建PdfViewer
        pdfViewer = new PdfViewer();
        pdfViewer.Dock = DockStyle.Fill;

        // 设置布局
        this.Controls.Add(toolStrip);
        this.Controls.Add(pdfViewer);
        toolStrip.Dock = DockStyle.Top;
    }

    private void LoadPdf()
    {
        try
        {
            // 检查文件是否存在
            if (!File.Exists(pdfFilePath))
            {
                MessageBox.Show($"PDF文件不存在: {pdfFilePath}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }

            // 加载PDF文件 - 保持Stream打开
            pdfStream = new FileStream(pdfFilePath, FileMode.Open, FileAccess.Read);
            pdfDocument = PdfDocument.Load(pdfStream);
            pdfViewer.Document = pdfDocument;
            
            // 设置默认缩放模式
            pdfViewer.ZoomMode = PdfViewerZoomMode.FitWidth;
        }
        catch (DllNotFoundException ex)
        {
            MessageBox.Show($"PDF预览组件未正确安装。请确保已安装PdfiumViewer.Native包。\n\n错误详情: {ex.Message}", 
                "PDF预览错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"无法加载PDF文件: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.Close();
        }
    }

    private void BtnFitWidth_Click(object? sender, EventArgs e)
    {
        try
        {
            pdfViewer.ZoomMode = PdfViewerZoomMode.FitWidth;
            // 强制刷新显示
            pdfViewer.Invalidate();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"设置适应宽度失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }

    private void BtnFitBest_Click(object? sender, EventArgs e)
    {
        try
        {
            pdfViewer.ZoomMode = PdfViewerZoomMode.FitBest;
            // 强制刷新显示
            pdfViewer.Invalidate();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"设置适应最佳失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }

    private void BtnOpenFolder_Click(object? sender, EventArgs e)
    {
        try
        {
            // 获取PDF文件所在目录
            string directory = Path.GetDirectoryName(pdfFilePath) ?? "";
            string fileName = Path.GetFileName(pdfFilePath);
            
            if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory))
            {
                MessageBox.Show($"目录不存在: {directory}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 使用explorer.exe打开目录并定位到文件
            var processStartInfo = new ProcessStartInfo
            {
                FileName = "explorer.exe",
                Arguments = $"/select,\"{pdfFilePath}\"",
                UseShellExecute = true
            };

            Process.Start(processStartInfo);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"打开文件夹失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        base.OnFormClosing(e);
        
        // 清理资源
        if (pdfDocument != null)
        {
            pdfDocument.Dispose();
            pdfDocument = null;
        }
        
        if (pdfStream != null)
        {
            pdfStream.Dispose();
            pdfStream = null;
        }
    }
} 